<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "apc_vote";
$title = "APC Voting System";

session_start(); //Starts the session in php
//Things that this will do:
//1. Check if user has logged in - Case1
//2. Check if the login is proper - Case2
//3. Don't go anywhere if login is improper or user has not logged in anymore
//   or has logged out - Case3


if(isset($_SESSION['userNum'])){//If user has logged in already because the session variable has been created
	$case = "case1";//Set the case to 'case1', to be used later
	$userNum = $_SESSION['userNum'];// sets the session to the userNum variable
	
	//Checks if the user's account has been accessed be 2 persons
	$ifLoginIsSingle = checkSessionID($_SESSION['sid'],$userNum,$server,$user,$pass,$db);
		
		//If account is accessed by more than 1 person, logs out the user
		if($ifLoginIsSingle == "False"){
			session_destroy(); 
			header('Location: home.php');
		}
	
    //Insert all database and user information to session variables for future use	
	$_SESSION['server'] = $server;
	$_SESSION['user'] = $user;
	$_SESSION['pass'] = $pass;
	$_SESSION['db'] = $db;
	$_SESSION['title'] = $title;
	
	//Set the overall site title as the pageTitle
	$pageTitle = $_SESSION['title'];
	
	//Set the login count to 0, meaning the account has been logged in successfully
	$_SESSION['loginCount'] = 0;
	
		
}else if($_POST["uname"] != "" && $_POST["password"] != ""){//If user has input a username and a password, not null, meaning a user logs in

	//First, check if the login is valid
	$isLoginCorrect = checkLogin($_POST["uname"],$_POST["password"],$server,$user,$pass,$db); //Check login details
	
	if($isLoginCorrect != "False"){ // If login is correct, sets the session variable.
		$_SESSION['userNum']=$isLoginCorrect;
		$userNum = $_SESSION['userNum']; // The userNum variable will be used to refer to the session variable
		insertAllInfoToSessions($userNum,$server,$user,$pass,$db);// Insert all voter info to session variables

		 //Insert all database and user information to session variables for future use	
		$_SESSION['server'] = $server;
		$_SESSION['user'] = $user;
		$_SESSION['pass'] = $pass;
		$_SESSION['db'] = $db;
		$_SESSION['title'] = $title;
	
		//Set the overall site title as the pageTitle
		$pageTitle = $_SESSION['title'];
		
		//Set the login count to 0, meaning the account has been logged in successfully
		$_SESSION['loginCount'] = 0;
		
		//Sets the case to 'case1', to be used later
		$case = "case1";
		
	}else{ //else don't do anything
		//increment the login attempts
		$_SESSION['loginCount'] = $_SESSION['loginCount'] + 1;
		$loginCount = $_SESSION['loginCount']; // Gets the login count
		$case = "case2"; // Show case2, to be uesd later
		$error = "Invalid Username or Password";//The error statement
	}
}else{

	//If the user has not logged in, and some login details are not complete, it will go to here
	if($_POST["uname"] == "" && $_POST["password"] == ""){ //If password and username is not inserted, no error will be seen
	$error = "";
	}else if($_POST["uname"] == "" || $_POST["password"] == ""){ //If the username or password is not inserted, ask the user to complete the login details
	$error = "Please complete the login details"; // the error statement
	}

	$case = "case2";// show case2, to be used later
	


}?>
<html>
<head>
<?php include('loadingScript.html'); ?>
<title>
<?php
	if($case == "case1"){ //If user has logged in succesfully, show this title
	echo "Welcome - ".$pageTitle."";
	}else{ // If it is not going anywhere, use this title instead
	echo "Login in to ".$title."";
	}
?>
</title>

<?php include('showIcon.php'); ?>

</head>
<body style="background-image:url('images/bg_blue.jpg')">
<div style="position:absolute;left:75px;top: 0px">
<table width = '810px' border="0" cellspacing="0" cellpadding="0">
<?php include("newsBanner.php"); ?>
</table>
<font face = "Arial">
<table style="width: 810px; height: 104px" border="0" cellspacing="0" cellpadding="0">
<?php
if($case == "case1"){ //If user has succesfully logged in, insert the menu buttons
include("menuButtons.php");
}else{ // Show only the header and the menu background
echo "<tr>";
echo "<td colspan='6' style='height: 104px'>";
echo "<img src='images/header.png'></td>";
echo "</tr>";
echo "</table><table style='width: 810px' background='images/menu.png' cellspacing='0' cellpadding='0' border='0'><tr><td width = '810px' height = '40px'></td></tr>";
}
?>
</table>
<table style="width: 810px;" cellspacing="0" cellpadding="0">
<tr>
<td style="height: 76px; width: 28px;"></td>
<td style="height: 76px" width="808px">
<?php
//-------------------------------------------------------------------------
//
//Check the case based from the steps taken above
//case1 = user successfully logs in
//      = Shows the contents of home page to user
//case2 = Shows the user errors in logging in, or if user just logged out
//
// -------------------------------------------------------------------------

if($case == "case1"){ //User has logged in last time - Use session variables

    
	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	
	$result = mysql_query("SELECT * FROM voters where voter_num =".$userNum) or die(mysql_error());  //Get all information from voter
	
	while($row = mysql_fetch_array( $result )){ //Show information
	
		echo "<br><h2>Welcome ".$row['voter_fname']." ".$row['voter_lname']."</h2>";
		echo "This is the APC voting system<br>";
		echo "<br>These are the functions of each page: <br>";
		echo "<br><b>Vote</b>-Proceed to voting<br>";
		echo "<b>Candidates</b>-View the candidate profiles<br>";
	
	if($row['voter_permission'] == "Admin"){ //If user is an admin, show this in the homepage
		echo "<b>Admin</b>-All administrative functions are found here<br>";
	}else{//If user is a voter, show this on the homepage
		echo "<b>Result</b>-If elections are closed, you can see the results here<br>";
	}
	
	echo "<br>Thank you for using this voting system<br>";
	echo "<br><br><hr><strong>Voter Information</strong><br>";
	echo "<font size = '2px'>";
	echo "Voter Number: ".$row['voter_num'];
	echo "<br>Account Type: ".$row['voter_permission'];
	
	}
}
		
if($case == "case2"){ //User logged out, or user is not logged in already
		
		//The login div
		echo "<div style='position:absolute;left:510px;top:225px;background-image:url(\"images/loginbg.png\");background-repeat:no-repeat;width:280px;height:120px;padding-left:10px;padding-top:10px;padding-right:10px;padding-right:10px'>";
		echo "<font color='red' size='2'>".$error."</font>"; //Where errors will show
		echo "<form action='home.php' method='POST'>";
		echo "<table cellpadding='2' width ='250px'>";
		echo "<tr><td align='right' width='180px'><font size ='2px'>User Name:</font></td> <td width='60px'><input type='text' name='uname' size='20'></td></tr><tr>";
		echo "<td align='right' width='180px'><font size ='2px'>Password: </font></td><td width='60px'><input name = 'password' type = 'Password' Size = '20'></td></tr><tr>";
		echo "<td></td><td align='right'><input type='submit' value='Login' ></td>";
		echo "</tr></table></form></div>";
		
		//The site description in the right
		echo "<br><table style='width:450px;font-size:14px'><tr><td><h3>What is APC Voting System?</h3></td></tr>";
		echo "<tr><td>This voting system is a web-based application that people can use ";
		echo "to see candidates, read their profiles, vote for them, and view the results ";
		echo "all in one website.</td></tr>";
		echo "<tr><td><br>This system has many features including:</td></tr>";
		echo "<tr><td><b>Easy Voting system</b> <br>- Voting can be done with just a few clicks, no more writing.</td></tr>";
		echo "<tr><td><b>Fast results</b> <br>- After the elections have been closed, voters can check the results already.</td></tr>";
		echo "<tr><td><b>Online candidate profiles</b> <br>- Tired of remembering who to vote? Read the profile of all candidates even during voting. Voters can see the picture, party belonging to, and a description of the candidate.</td></tr>";
		echo "<tr><td><b>News update</b> <br>- Want to keep track of the election results. Admin can post news so that you can know what are the current results as of that moment.</td></tr>";
		echo "<tr><td><b>Admin Functions</b> <br>- Administrators can add candidates and positions and track results.</td></tr></table>";
		
		
}
//Function checkLogin
// Function accepts the ff parameters:
// userID = the user name input
// userPass = input password
// sver,usr,passwd,dbase - information for database connection
function checkLogin($userID,$userPass,$sver,$usr,$passwd,$dbase){

		mysql_connect($sver,$usr,$passwd) or die(mysql_error());
		mysql_select_db($dbase) or die(mysql_error());
		$result = mysql_query("SELECT * FROM voters where voter_username= '".$userID."' AND voter_pass = '".$userPass."'") or die(mysql_error()); //check whether an entry exist w/ the given username and password
		
		while($row = mysql_fetch_array( $result )){
	
			$checkVoterNum = $row['voter_num'];
		}
		
		if($checkVoterNum == ""){
		
			return "False"; // if there are no results, return false
			
		}else if($checkVoterNum < 0){
		
			return "False"; // if there are no results, return false
		
		}else{
			return $checkVoterNum; // else, return true
		}
}

//Function insertAllInfoToSessions()
// -Gets all voter info, then puts it in 
// session variables to be accessed at any page.
function insertAllInfoToSessions($userNumber,$sver,$usr,$passwd,$dbase){
mysql_connect($sver,$usr,$passwd) or die(mysql_error());
mysql_select_db($dbase) or die(mysql_error());

$randomSessionId = uniqid(rand());
$_SESSION['sid'] = $randomSessionId;

mysql_query("UPDATE voters SET voter_current_session =  '".$randomSessionId ."' WHERE voter_num = '".$userNumber."'") or die(mysql_error());
$info = mysql_query("Select * from voters where voter_num = '".$userNumber."'") or die(mysql_error());
	while($infoLine = mysql_fetch_array($info)){
	$_SESSION['voter_permission'] = $infoLine['voter_permission'];
	$_SESSION['voter_lname'] = $infoLine['voter_lname'];
	$_SESSION['voter_fname'] = $infoLine['voter_fname'];
	}
}

//Function checkSessionID()
// -Checks if session in db is same in the session in browser
// If not, it logs out
function checkSessionID($sid,$uname,$sver,$usr,$passwd,$dbase){
mysql_connect($sver,$usr,$passwd) or die(mysql_error());
mysql_select_db($dbase) or die(mysql_error());

	$querySession = mysql_query("SELECT voter_current_session from voters WHERE voter_num = '".$uname."'");	

		while($sessionInDB = mysql_fetch_array($querySession)){
		$loggedSession = $sessionInDB['voter_current_session'];
		}

	if($_SESSION['sid'] == $loggedSession){
	return "True"; //If the sessionID saved in the browser of the user is same as in the database, means that the account has been used by a single user
	}else{
	return "False";//If another person accesssed the same account, returns false
	}	
}
?>
</td>
</tr>
</table>
<br><br><br><br><br>
</div>
<?php include('bottomLinks.php'); ?>
</body>
</html>
